#!/bin/bash
###
# @Author: Logan.Li
# @Date: 2025-09-08 23:55:00
# @LastEditTime: 2025-09-08 23:55:00
# @Description: MySQL 8.0服务安装配置脚本
# @支持系统: RHEL/CentOS/Rocky/AlmaLinux/Amazon Linux 2/Amazon Linux 2023/Debian/Ubuntu
###
# curl -s https://gitee.com/attacker/All-In-One-Ops/raw/master/1.scripts/services/mysql8.sh | bash

# 基础设置
set -e  # 遇到错误立即退出

# 简洁输出函数
info() { echo -e "\e[34m[INFO]\e[0m $1"; }
warn() { echo -e "\e[33m[WARN]\e[0m $1"; }
error() { echo -e "\e[31m[ERROR]\e[0m $1" >&2; }
success() { echo -e "\e[32m[SUCCESS]\e[0m $1"; }

# 检查系统类型
check_system() {
    if [[ -f /etc/os-release ]] && grep -q "Amazon Linux" /etc/os-release; then
        echo "rhel"
    elif [[ -f /etc/redhat-release ]]; then
        echo "rhel"
    elif [[ -f /etc/debian_version ]]; then
        echo "debian"
    else
        error "不支持的操作系统"
        exit 1
    fi
}

# 卸载MariaDB
remove_mariadb() {
    info "检查并卸载MariaDB..."
    
    local system_type=$(check_system)
    
    if [[ "$system_type" == "rhel" ]]; then
        if rpm -qa | grep -i mariadb &> /dev/null; then
            warn "发现MariaDB，正在卸载..."
            yum remove mariadb* -y
            success "MariaDB卸载完成"
        else
            info "未发现MariaDB"
        fi
    elif [[ "$system_type" == "debian" ]]; then
        if dpkg -l | grep -i mariadb &> /dev/null; then
            warn "发现MariaDB，正在卸载..."
            apt-get remove --purge mariadb* -y
            apt-get autoremove -y
            success "MariaDB卸载完成"
        else
            info "未发现MariaDB"
        fi
    fi
}

# 安装MySQL 8.0
install_mysql8() {
    local system_type=$(check_system)
    
    info "开始安装MySQL 8.0..."
    
    if [[ "$system_type" == "rhel" ]]; then
        # RHEL/CentOS/Amazon Linux系统
        info "添加MySQL官方仓库..."
        
        # 检测系统版本
        if [[ -f /etc/os-release ]]; then
            . /etc/os-release
            if [[ "$ID" == "amzn" ]]; then
                # Amazon Linux
                if [[ "$VERSION_ID" == "2" ]]; then
                    rpm -Uvh https://repo.mysql.com/mysql80-community-release-el7.rpm
                else
                    rpm -Uvh https://repo.mysql.com/mysql80-community-release-el8.rpm
                fi
            elif [[ "$VERSION_ID" =~ ^7 ]]; then
                rpm -Uvh https://repo.mysql.com/mysql80-community-release-el7.rpm
            elif [[ "$VERSION_ID" =~ ^8 ]]; then
                rpm -Uvh https://repo.mysql.com/mysql80-community-release-el8.rpm
            elif [[ "$VERSION_ID" =~ ^9 ]]; then
                rpm -Uvh https://repo.mysql.com/mysql80-community-release-el9.rpm
            else
                rpm -Uvh https://repo.mysql.com/mysql80-community-release-el8.rpm
            fi
        else
            rpm -Uvh https://repo.mysql.com/mysql80-community-release-el7.rpm
        fi
        
        # 安装MySQL
        if command -v dnf &> /dev/null; then
            dnf install -y mysql-community-server
        else
            yum install -y mysql-community-server
        fi
        
    elif [[ "$system_type" == "debian" ]]; then
        # Debian/Ubuntu系统
        info "添加MySQL官方仓库..."
        
        apt-get update
        apt-get install -y wget lsb-release gnupg
        
        # 下载并安装MySQL APT仓库配置包
        wget https://dev.mysql.com/get/mysql-apt-config_0.8.29-1_all.deb
        DEBIAN_FRONTEND=noninteractive dpkg -i mysql-apt-config_0.8.29-1_all.deb
        
        apt-get update
        
        # 预设MySQL root密码（可选）
        echo "mysql-community-server mysql-community-server/root-pass password" | debconf-set-selections
        echo "mysql-community-server mysql-community-server/re-root-pass password" | debconf-set-selections
        
        DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-community-server
        
        # 清理下载的包
        rm -f mysql-apt-config_0.8.29-1_all.deb
    fi
    
    success "MySQL 8.0安装完成"
}

# 配置MySQL
configure_mysql() {
    info "配置MySQL..."
    
    # 创建自定义配置文件
    cat > /etc/mysql/conf.d/custom.cnf << 'EOF'
[mysqld]
# 基础配置
bind-address = 0.0.0.0
max_connections = 1000

# 字符集配置
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

# InnoDB性能优化
innodb_buffer_pool_size = 1G
innodb_flush_log_at_trx_commit = 2

# 日志配置
slow_query_log = 1
long_query_time = 2

[mysql]
default-character-set = utf8mb4

[client]
default-character-set = utf8mb4
EOF

    # 创建日志目录
    mkdir -p /var/log/mysql
    chown mysql:mysql /var/log/mysql
    
    success "MySQL配置完成"
}

# 启动MySQL服务
start_mysql() {
    info "启动MySQL服务..."
    
    systemctl enable mysqld
    systemctl start mysqld
    
    # 等待服务启动
    sleep 5
    
    if systemctl is-active --quiet mysqld; then
        success "MySQL服务启动成功"
    else
        error "MySQL服务启动失败"
        systemctl status mysqld
        exit 1
    fi
}

# 获取临时密码并进行安全设置
secure_mysql() {
    info "配置MySQL安全设置..."
    
    # 获取临时密码
    if [[ -f /var/log/mysqld.log ]]; then
        TEMP_PASSWORD=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}' | tail -1)
        
        if [[ -n "$TEMP_PASSWORD" ]]; then
            success "找到临时密码: $TEMP_PASSWORD"
            
            # 提示用户设置新密码
            echo ""
            echo "========================================="
            echo "MySQL 8.0安装完成！"
            echo "临时密码: $TEMP_PASSWORD"
            echo "========================================="
            echo ""
            info "请使用以下命令登录并设置新密码:"
            echo "mysql -u root -p"
            echo ""
            info "登录后执行以下SQL命令设置新密码:"
            echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '新密码';"
            echo "FLUSH PRIVILEGES;"
            echo ""
            info "或者运行mysql_secure_installation进行安全配置:"
            echo "mysql_secure_installation"
            
        else
            warn "未找到临时密码，可能是无密码安装"
        fi
    else
        warn "未找到MySQL日志文件"
    fi
}

# 显示服务信息
show_info() {
    info "MySQL服务信息:"
    info "端口: 3306"
    info "配置文件: /etc/mysql/conf.d/custom.cnf"
    info "错误日志: /var/log/mysql/error.log"
    info "慢查询日志: /var/log/mysql/slow.log"
    info "数据目录: /var/lib/mysql"
    
    # 显示版本信息
    if command -v mysql &> /dev/null; then
        local mysql_version=$(mysql --version | awk '{print $3}' | cut -d',' -f1)
        info "MySQL版本: $mysql_version"
    fi
}

# 主函数
main() {
    info "开始安装MySQL 8.0服务..."
    
    # 检查是否已安装
    if systemctl is-active --quiet mysqld 2>/dev/null; then
        success "MySQL已安装并运行中"
        systemctl status mysqld --no-pager
        show_info
        exit 0
    fi
    
    remove_mariadb
    install_mysql8
    configure_mysql
    start_mysql
    secure_mysql
    show_info
    
    success "MySQL 8.0安装和配置完成！"
}

# 执行主函数
main "$@"
